package com.unionfind;

/**
 * @Author: tgy
 * @Date: 2020-10-20 10:31
 */
public class UnionFind_QU extends AbstractUnionFind {

    public UnionFind_QU(int capacity) {
        super(capacity);
    }

    @Override
    protected int find(int v) {

        checkV(v);

        while (parents[v] != v) {
            v = parents[v];
        }

        return v;
    }

    /**
     * 把v1的根节点的parent指向v2的根节点
     * @param v1 节点
     * @param v2 节点
     */
    @Override
    protected void union(int v1, int v2) {

        int parentV1 = find(v1);
        int parentV2 = find(v2);

        if (parentV1 == parentV2) {
            return;
        }

        assignParent(parentV1,parentV2);
    }

    protected void assignParent(int pv1,int pv2) {

        parents[pv1] = pv2;
    }
}
